package org.lwj.logger.support;

import org.lwj.logger.clazz.Loader;
import org.lwj.logger.http.HttpHeadType;
import org.lwj.logger.mdc.LogMdc;
import org.lwj.logger.name.AppNameLoader;
import org.lwj.logger.util.Constant;
import org.lwj.logger.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http head 静态设值
 * 
 * @author liwenjian
 *
 */
public class HttpLog extends Loader<HttpHeadType> {
	private final static Logger logger = LoggerFactory.getLogger(HttpLog.class);
	private static String appName = AppNameLoader.appName();

	private static HttpLog loader = new HttpLog();

	public static HttpLog instance() {
		return loader;
	}

	private HttpLog() {
		addClazz("java.net.URLConnection", "org.sky.logger.http.support.URLConnetionHeadType");
		addClazz("org.apache.http.HttpMessage", "org.sky.logger.http.support.HttpClientHeadType");
		addClazz("org.springframework.http.HttpMessage", "org.sky.logger.http.support.HttpMessageHeadType");
		addClazz("feign.RequestTemplate", "org.sky.logger.http.support.FeignHeadType");
	}

	public Class<HttpHeadType> objectType() {
		return HttpHeadType.class;
	}

	/**
	 * http head 添加 AppName 和 LogId
	 * 
	 * @param head
	 * @return
	 */
	public static boolean addHead(Object head) {
		String appName = getAppName();
		String logid = LogMdc.get(Constant.LogId);
		if (Util.isEmpty(logid)) {
			logid = Util.logId();
		}
		for (int i = 0; i < instance().size(); ++i) {
			HttpHeadType headType = instance().getObject(i);
			boolean nsuccees = headType.addHead(head, Constant.AppName, appName);
			boolean lsuccees = headType.addHead(head, Constant.LogId, logid);
			if (nsuccees && lsuccees) {
				logger.info("HttpLog appName logid : " + appName + " " + logid);
				return true;
			}
		}
		return false;
	}

	public static String getAppName() {
		return appName;
	}

	public static void setAppName(String appName) {
		HttpLog.appName = appName;
	}

}
